<template>
  <div class="main">
    <div class="search-div">
      <el-input placeholder="请输入查询内容" v-model="query">
        <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
      </el-input>
      <el-button type="success" @click="openAddUser">新增</el-button>
    </div>
    <el-table :data="users" stripe border style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
            @change="changeState(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="prev, pager, next,sizes , total"
      :total="total"
      :page-size="pagesize"
      :page-sizes="[5, 10, 30, 100,500]"
    ></el-pagination>

    <!---------------------新增表单------------------------------------->
    <el-dialog :title="formName" :visible.sync="formVisible" @close="closeForm">
      <el-form :model="user" :rules="rules" ref="formRef">
        <el-input v-show="false" v-model="user.id"></el-input>
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input v-model="user.username" :disabled="formName == '编辑用户'"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-input v-model="user.password" :disabled="formName == '编辑用户'"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px" prop="email">
          <el-input v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="120px" prop="mobile">
          <el-input v-model="user.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  mounted: function() {
    this.$emit("return-path", ["用户管理", "用户列表"]);
    this.getUsers();
  },
  data() {
    return {
      users: [],
      pagenum: 1,
      pagesize: 5,
      total: 0,
      query: "",
      user: {
        id: "",
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      formVisible: false,
      formName: "",
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 10, message: "长度在 6 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    async getUsers() {
      const { data: res } = await this.$http.get(
        "/users?pagenum=" +
          this.pagenum +
          "&pagesize=" +
          this.pagesize +
          "&query=" +
          this.query
      );
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.users = res.data.users;
      this.total = res.data.total;
    },
    async handleEdit(index, row) {
      const { data: res } = await this.$http.get("/users/" + row.id);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.user = res.data;
      this.user.password = "******";
      this.formVisible = true;
      this.formName = "编辑用户";
    },
    handleDelete(index, row) {
      this.$messageBox
        .confirm(
          "此操作将会永久删除用户" + row.username + ", 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
        .then(async () => {
          const { data: res } = await this.$http.delete("/users/" + row.id);
          if (res.meta.status != 200) return this.$message.error(res.meta.msg);
          this.getUsers();
          return this.$message.success(res.meta.msg + "!");
        });
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.getUsers();
    },
    handleCurrentChange(val) {
      this.pagenum = val;
      this.getUsers();
    },
    //修改用户状态
    changeState(val) {
      this.$messageBox
        .confirm(
          "此操作将会修改用户" + val.username + "的状态, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
        .then(async () => {
          const { data: res } = await this.$http.put(
            "/users/" + val.id + "/state/" + val.mg_state
          );
          if (res.meta.status != 200) {
            val.mg_state = !val.mg_state;
            return this.$message.error(res.meta.msg);
          }
          return this.$message.success(res.meta.msg + "!");
        })
        .catch(() => {
          val.mg_state = !val.mg_state;
          return this.$message.info("取消修改");
        });
    },
    //新增用户页面
    openAddUser() {
      this.formVisible = true;
      this.formName = "新增用户";
    },
    //保存用户方法
    saveUser() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        if (!this.user.id) {
          //新增方法
          const { data: res } = await this.$http.post("/users", this.user);
          if (res.meta.status != 200 && res.meta.status != 201) {
            return this.$message.error(res.meta.msg);
          }
          this.formVisible = false;
          this.$message.success(res.meta.msg + "!");
        } else {
          //修改
          const { data: res } = await this.$http.put("/users/" + this.user.id, this.user);
          if (res.meta.status != 200 && res.meta.status != 201) {
            return this.$message.error(res.meta.msg);
          }
          this.formVisible = false;
          this.$message.success(res.meta.msg + "!");
        }
        this.getUsers();
      });
    },
    closeForm() {
      this.formName = "";
      this.$refs.formRef.resetFields();
    }
  }
};
</script>

<style lang='less' scoped>
.main {
  background-size: 100% 100%;
  height: 100%;
  width: 100%;

  .el-pagination {
    font-weight: 400;
    margin-top: 10px;
  }
  .search-div {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    .el-input {
      width: 40%;
    }
  }
}

.el-dialog {
  .el-input {
    width: 50%;
  }
}
</style>
